<template>
  <section>
    <el-popover ref="popover4" v-model="visible2" placement="bottom" width="500" trigger="click">
      <div class="popover">
        <h3>选择文件</h3>
        <div class="hd clearfix">
          <div class="flo-l">
            <span @click="homeBut"><i class="fa fa-home"></i>Home</span>&emsp;&emsp;
            <!--<span><i class="fa fa-folder-open"></i>工作区</span>-->
          </div>
          <div class="flo-l mbx">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item v-for="item in hdfs_dirs">{{item}}</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
        </div>

        <div class="md">
          <div class="folderList" @dblclick="handleDbc({hdfs_path:'..'})"
               @click="handleFloder({hdfs_path:'..'})">
            <span><i class="fa fa-folder-open"></i></span>
            <span>..</span>
          </div>
          <div v-for="(item,index) in folderData">
            <div :class="`folderList ${item.selected?'selbg':''}`" data-index @dblclick="handleDbc(item)"
                 @click="handleFloder(item)">
              <span v-if="item.isdirectory ==0"><i class="fa fa-file"></i></span>
              <span v-else-if="item.isdirectory ==1"><i class="fa fa-folder"></i></span>
              <span v-else><i class="fa fa-file-o"></i></span>
              <span>{{item.file_name}}</span>
            </div>
          </div>
        </div>

        <div class="ft">
          <div class="btn">
            <el-upload
              style="float: left;width: 100px;"
              v-if="uploadTypet != 0"
              :action="uploadUrl"
              :headers="headers"
              :data="uploadBody"
              multiple
              :on-success="handleAvatarSuccess"
              :on-error="handleAvatarError"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :show-file-list=false
              :file-list="fileList">
              <el-button type="primary">点击上传</el-button>
            </el-upload>
            <el-button type="primary" @click="selDir">选择此项</el-button>
            <el-button type="primary" @click="toggleCreatFolder">创建新文件夹</el-button>
          </div>
          <div class="createFolder" v-show="createFolder">
            <div>
              <el-input style="width:200px;" v-model="createFolderInput" :rows="2"
                        placeholder="请输入文件夹名字"></el-input>
            </div>
            <el-button type="primary" @click="handleCreatFolder">创建文件夹</el-button>
            <el-button type="primary" @click="handleCancleFolder">取消</el-button>
          </div>
        </div>
      </div>
    </el-popover>
    <div class="uploadwarn">
      <el-row>
        <el-col :span="19">
          <el-input style="border-right: 0;" v-model="folderPath" :placeholder="placeholder||'请选择路径'"
                    @change="inpcg"></el-input>
        </el-col>
        <el-col :span="5">
          <el-button @click="findByPathHttp()" style="margin-left: 1px;" v-popover:popover4><i class="fa fa-cloud-upload"></i></el-button>
        </el-col>
      </el-row>
    </div>
  </section>
</template>
<script>
  import util from '../common/util'
  import dao from '../common/dao'
  import C from '../common/cfg'
  import { mapGetters } from 'vuex'

  export default {
    components: {},
    props: ['uploadType', 'value', 'disabled', 'placeholder'],
    computed: {
      ...mapGetters([
        'getUser',
      ])
    },
    data () {
      return {
        fun: null,
        fileList: [],
        uploadUrl: `${C.APIURL}bdpmng/service/datamgt/hdfs/upload`,
        headers: {
          Authentication: C.HEADERS.Authentication,
          RJDATACENTERID: `${util.fetch('dataCenterId')}`
        },
        role: {
          role_id: '',
          role_name: '',
          tenant: []
        },
        tenant_id: '',
        uploadBody: {hdfs_dir: ''},
        hdfs_dir: '',
        hdfs_dirs: [],
        visible2: false,
        uploadTypet: this.uploadType, // 0：不可上传 1：可以上传 2：角色管理-数据权限HDFS 上传路径
        folderData: [], //文件夹信息
        createFolder: false, //是否创建新文件夹
        createFolderInput: '', //创建新文件夹的名字
        folderPath: this.value || '', //文件夹路径
        chooseFolderPath: [], //选中的文件夹路径
        chooseFilePath: [], //选中的文件路径
      }
    },
    watch: {
      value: function (newValue, oldValue) {
        this.folderPath = this.value;
      },
    },
    methods: {
      handlePreview () {},
      handleRemove () {},
      inpcg () {
        this.setCurrentValue(this.folderPath)
      },
      findByPathHttp (hdfs_dir) {
        let arg = {"hdfs_dir": `${(hdfs_dir || this.hdfs_dir)}`};
        if (this.uploadType == 2) {
          this.role = util.fetch('page212_role');
          this.tenant_id = util.fetch('page212_tenement'); //获取租户ID
          arg.tenant_id = this.tenant_id;
        }

        dao[this.fun](arg).then((response) => {
          if (response.FX.err) { return false }
          let pageRes = response.body || {};
          this.hdfs_dir = pageRes.current_path;
          this.uploadBody = {hdfs_dir: this.hdfs_dir};
          this.uploadUrl = `${C.APIURL}bdpmng/service/datamgt/hdfs/upload?hdfs_dir=${this.hdfs_dir}`;
          this.hdfs_dirs = this.dir2dirs(this.hdfs_dir);
          let hdfs_files_list = (pageRes.hdfs_files_list || []).map(item => {
            item.selected = false;
            return item;
          });
          this.folderData = hdfs_files_list;
        })

      },
      toBack(){
        let arr = [];
        if (this.hdfs_dirs.length == 0) {
        } else {
          arr = JSON.parse(JSON.stringify(this.hdfs_dirs))
          arr.pop();
        }
        let p = this.dirs2dir(arr);
        this.findByPathHttp(p)
      },
      handleFloder (item) { //单击文件
        this.folderData.map(one => {
          one.selected = false;
        });
        item.selected = item.selected ? false : true;
      },
      handleDbc (item) { //双击文件
        if (item.hdfs_path == '..') {
          this.toBack();
          return false;
        } else if (item.isdirectory == '1') {
          let arr = JSON.parse(JSON.stringify(this.hdfs_dirs));
          arr.push(item.file_name);
          let p = this.dirs2dir(arr);
          this.findByPathHttp(p)
        }
      },
      toggleCreatFolder () { //是否显示创建
        this.createFolder = (this.createFolder == true) ? false : true;
        this.createFolderInput = ""
      },
      handleSuccess () {
        this.findByPathHttp();
      },
      handleCreatFolder () { //创建文件夹

        let hdfs_dir = this.hdfs_dir;
        let file_name = this.createFolderInput;
        if (!file_name)return false;
        dao.mkdir({file_name, hdfs_dir}).then(res => {

          if (!res.body || res.body.retCode != 200) return false;
          let retCode = res.body.retCode || 0;
          util.callbackTips(retCode);
          this.findByPathHttp();
          this.toggleCreatFolder();

        })

      },
      handleCancleFolder () { //删除文件夹
        this.createFolder = false;
        this.createFolderInput = "";
      },
      selDir(){
        for (let item of this.folderData) {
          if (item.selected == true) {
            this.folderPath = item.hdfs_path;
            break;
          }
        }
        if (this.folderPath.length <= 0)return false;
        this.visible2 = false;
        this.setCurrentValue(this.folderPath)
      },
      dir2dirs(str){
        let hdfs_dirs = [];
        (str || '').split('/').map(item => {
          if (item != '') hdfs_dirs.push(item);
        })
        return hdfs_dirs
      },
      dirs2dir(arr){
        let hdfs_dirs = arr || [];
        let str = '/';
        hdfs_dirs.map(item => {
          str += `${item}/`
        });
        return str
      },
      homeBut () {
        this.findByPathHttp(`${C.tenentRoot}/`)
      },
      setCurrentValue (value) {

        this.$emit('input', value);
        this.$emit('change', value);

      },
      handleAvatarSuccess(response, file, fileList){ //上传成功回调
        util.callbackTips(response);
        this.findByPathHttp();
      },
      handleAvatarError(response, file, fileList){ //上传失败回调
        util.callbackTips(response);
      }
    },
    mounted () {

      if (this.uploadType == 2) {
        this.fun = 'findByPathHdfs';
      } else {
        this.fun = 'findByPath';
      }
      this.hdfs_dir = this.dirs2dir(this.dir2dirs(C.tenentRoot));
      this.findByPathHttp();

    }
  }
</script>

<style scoped>
  .uploadwarn {
    position: relative;
    /*width: 300px;*/
  }

  div.popover {
    padding: 0px 10px 20px 10px;
  }

  .el-popover .hd > div {
    display: inline-block;
  }

  .el-popover span {
    font-size: 16px;
  }

  div.popover .hd i {
    font-size: 18px;
  }

  div.popover .hd span {
    cursor: pointer;
  }

  .el-popover .md {
    padding: 5px;
    margin-top: 20px;
    max-height: 250px;
    border: 1px solid #f1f1f1;
    overflow: auto;
  }

  .el-popover__title,
  .el-breadcrumb {
    font-size: 16px;
  }

  .el-popover {
    font-size: 16px;
  }

  .el-upload {
    display: inline-block;
    width: auto;
  }

  i.fa {
    padding-right: 5px;
    color: #20a0ff;
  }

  .folderList {
    cursor: pointer;
  }

  .el-popover .ft {
    margin-top: 20px;
  }

  .createFolder {
    margin-top: 20px;
  }

  .createFolder div {
    display: inline-block;
  }

  div.folderList:hover {
    background-color: #c7e7ff;
  }

  .selbg {
    background-color: #c7e7ff;
  }

  .mbx {
    padding-left: 10px;
  }

  .mbx span {
    line-height: 22px;
  }

  .btn > div {
    margin-bottom: 10px;
  }


</style>